package com.xiaoyu.lanling.feature.checkin

import `in`.srain.cube.views.list.CubeRecyclerViewSimpleAdapter
import android.content.DialogInterface
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.ErrorMessageEvent
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseDialogFragment
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.checkin.CheckInDialogDismissEvent
import com.xiaoyu.lanling.event.checkin.CheckInEvent
import com.xiaoyu.lanling.feature.checkin.data.CheckInData
import com.xiaoyu.lanling.feature.checkin.datamodel.CheckInDailyItem
import com.xiaoyu.lanling.feature.checkin.datamodel.CheckInInfo
import com.xiaoyu.lanling.feature.checkin.log.CheckInLogger
import com.xiaoyu.lanling.feature.checkin.viewholder.CheckInDailyViewHolder
import kotlinx.android.synthetic.main.check_in_dialog.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CheckInDialogFragment : BaseDialogFragment(), BaseDialogFragment.OnDismissListener {

    companion object {
        val TAG: String = CheckInDialogFragment::class.java.simpleName

        fun show(fragmentManager: FragmentManager, checkInInfo: CheckInInfo, from: String) {
            val params = Bundle()
            params.putSerializable(Constant.IntentKey.KEY_CHECK_IN_INFO, checkInInfo)
            params.putString(Constant.PARAM_FROM, from)

            val fragment = CheckInDialogFragment()
            fragment.arguments = params
            fragment.show(fragmentManager, TAG)
        }
    }

    private val requestTag = Any()
    private val adapter = CubeRecyclerViewSimpleAdapter<CheckInDailyItem>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreenDimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return layoutInflater.inflate(R.layout.check_in_dialog, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        super.onViewCreatedSafelyAfterAppFinishInit(view, savedInstanceState)
        initView()
        initBind()
        initEvent()
        logEventForEnter()
    }

    private fun logEventForEnter() {
        val from = arguments?.getString(Constant.PARAM_FROM, "") ?: ""
        CheckInLogger.show(from)
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        val from = arguments?.getString(Constant.PARAM_FROM, "") ?: ""
        if (from == Constant.From.PUSH) {
            CheckInDialogDismissEvent().post()
        }
    }

    private fun initView() {
        val checkInInfo = arguments?.getSerializable(Constant.IntentKey.KEY_CHECK_IN_INFO) as? CheckInInfo
                ?: return
        check_in_days_desc.text = getCheckInDaysDesc(checkInInfo.checkInDays)

        adapter.setViewHolderClass(0, null, CheckInDailyViewHolder::class.java, 7)
        days_recyclerview.adapter = adapter

        adapter.list = checkInInfo.list
        adapter.notifyDataSetChanged()
    }

    private fun initBind() {
        view?.setOnClickDebounceListener { dismiss() }
        close?.setOnClickDebounceListener { dismiss() }
        check_in_button?.setOnClickDebounceListener {
            check_in_button?.isEnabled = false
            CheckInData.checkIn(requestTag)
            CheckInLogger.checkInRequestStart()
        }
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CheckInEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                if (event.isFailed) {
                    event.failData.exception.message?.let {
                        CheckInLogger.checkInRequestFailure(it)
                    }
                } else {
                    showCheckInSuccessDialog(event)
                    CheckInLogger.checkInRequestSuccess()
                }
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: ErrorMessageEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                check_in_button?.isEnabled = true
            }
        })
    }

    private fun showCheckInSuccessDialog(event: CheckInEvent) {
        CheckInSuccessDialogFragment.show(childFragmentManager, event.model, this)
    }

    private fun getCheckInDaysDesc(days: Int): SpannableString {
        val daysString = days.toString()
        val title = SpannableString(getString(R.string.check_in_days_desc, daysString))
        val start = title.indexOf(daysString)
        val end = start + daysString.length
        title.setSpan(ForegroundColorSpan(AppContext.getColor(R.color.colorOnSecondary)), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        title.setSpan(RelativeSizeSpan(1.7F), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        return title
    }

    override fun onDismiss() {
        dismiss()
    }
}